<template>
  <div class="tree-container">
    <div class="tree-header" v-if="treeData.length">
      <div class="expand-all-btn" @click="toggleAllItems">
        <img src="../../assets/layerTree/收起展开全部@2x.png" alt="收起展开全部">
        {{ allExpanded ? '收起图层' : '展开图层' }}
      </div>
    </div>
    <el-tree show-checkbox empty-text="暂无数据" element-loading-background="rgba(122, 122, 122, 0.5)"
      v-loading="loadingTree" ref="treeRef" :data="treeData" :props="defaultProps" :expand-on-click-node="false"
      node-key="id" @node-click="handleNodeClick" :default-expand-all="allExpanded" :filter-node-method="filterNode"
      @check="handleCheck">
      <template #default="{ node, data }">
        <div class="custom-tree-node" @mouseenter="data.showBtns = true" @mouseleave="data.showBtns = false">
          <div class="node-content" :class="getNodeClass(node.level)" :style="getNodeStyle(node, data)">
            <img v-if="data.nodeType === 0" src="@/assets/layerTree/文件图标.png" alt="文件" class="folder-icon">
            <span class="item-text">{{ data.label }}</span>
            <span class="item-count" v-if="data?.nodeType === 0">({{ data?.layerCount }})</span>
            <el-select :suffix-icon="IconDropDownYear" v-if="[0, 1].includes(showPanelNo) && data.timingNodes"
              :show-arrow="false" popper-class="select_dark_popper" class="yearSelect" v-model="data.defaultId"
              placeholder="请选择" size="small">
              <el-option v-for="year in data.timingNodes" :key="year.id" :label="year.nodePhase" :value="year.id">
              </el-option>
            </el-select>
            <!-- 叠加图层下移上移操作 -->
            <div class="move-btns" v-show="data.showBtns" v-if="data.nodeType === 1 && showPanelNo === 3">
              <img @click.stop="moveUp(data)" src="../../assets/layerTree/上移@2x.png" alt="上移" />
              <img @click.stop="moveDown(data)" src="../../assets/layerTree/下移@2x.png" alt="下移" />
            </div>
            <!-- 更多 -->
            <el-popover :show-arrow="false" popper-class="popver-tree" :width="150" trigger="click" placement="bottom">
              <template #reference>
                <el-icon v-show="data.showBtns" class="more" v-if="data.nodeType !== 0">
                  <MoreFilled />
                </el-icon>
              </template>
              <ul class="popover-list">
                <li class="popover-item" v-for="(i, n) in menuConfig" :key="n" @click.stop="i.click(data)">
                  <img :src="i.src" :alt="i.name">
                  {{ i.name }}
                </li>
              </ul>
            </el-popover>
          </div>
          <!-- 操作按钮 -->
          <div v-show="data.showBtns" v-if="data?.children?.length && [2, 3].includes(showPanelNo)" class="showBtns">
            <img @click.stop="addGroup" style="width:16px;height:16px" src="../../assets/layerTree/添加图层@2x.png"
              alt="添加图层">
            <img @click.stop="addGroup(data)" style="width:16px;height:16px;margin:0 8px"
              src="../../assets/layerTree/填写-编辑@2x.png" alt="编辑">
            <img @click.stop="deleteGroup" style="width:16px;height:16px" src="../../assets/layerTree/删除@2x.png"
              alt="删除">
          </div>
        </div>
      </template>
    </el-tree>
    <!-- 新增分组 -->
    <el-button v-if="[2, 3].includes(showPanelNo)" type="primary"
      style="width: 100%;background-color: #016EAB;border-color: #016EAB;" @click="addGroup">
      <img src="../../assets/layerTree/新增分组@2x.png" style="width:16px;height: 16px;margin-right: 5px;" alt="新增分组">
      新增分组</el-button>
  </div>
  <!-- 底部标签 -->
  <div class="bottom-tabs">
    <div class="item-custom common-css" :style="showPanelNo !== 0 ? 'background-color: #13161E;' : ''"
      @click="changePanel(0)">
      <el-dropdown trigger="click" popper-class="select_dark_popper" :style="showPanelNo === 0 ? wrapperStyle : ''">
        <div class="dropdown-trigger">
          <span>{{(customLayerList?.find(i => i.id === customLasyer)?.catalogName)?.length > 6 ?
            (customLayerList?.find(i => i.id === customLasyer)?.catalogName)?.slice(0, 6) + '...' :
            customLayerList?.find(i => i.id === customLasyer)?.catalogName || '选择图层'}}</span>
          <img src="@/assets/layerTree/上拉@2x.png" style="width: 24px; height: 24px;object-fit: contain;" alt="上拉" />
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="item in customLayerList" :key="item.id" @click="changeCustomLayer(item.id)">
              <img style="width: 16px; height: 16px; margin-right: 8px; pointer-events: auto;"
                :src="getSelectIcon(item)" alt="自定义图层选中" @click.stop="handleUpdateDefaultLayer(item.id)">
              <span>{{ item.catalogName }}</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

    </div>
    <div class="common-css item-all"
      :style="[showPanelNo === 1 ? wrapperStyle : '', showPanelNo !== 1 ? 'background-color: #13161E;' : '']"
      @click="changePanel(1)">全部</div>
    <div class="item-collect common-css"
      :style="[showPanelNo === 2 ? wrapperStyle : '', showPanelNo !== 2 ? 'background-color: #13161E;' : '']"
      @click="changePanel(2)">收藏</div>
    <div class="item-overlay common-css"
      :style="[showPanelNo === 3 ? wrapperStyle : '', showPanelNo !== 3 ? 'background-color: #13161E;' : '']"
      @click="changePanel(3)">叠加</div>
  </div>
  <AddGroupModal ref="addGroupModalRef"></AddGroupModal>
</template>

<script setup>
import { ref, computed, getCurrentInstance, onMounted } from 'vue'
import useLayerStore from "@/store/modules/layer.js";
import customLayerBg from '@/assets/layerTree/自定义图层.png'
import allLayerBg from '@/assets/layerTree/全部.png'
import djLayerBg from '@/assets/layerTree/叠加.png'
import sc from '../../assets/layerTree/收藏@2x.png'
import qt from '../../assets/layerTree/全图icon@2x.png'
import sjz from '../../assets/layerTree/时间轴@2x.png'
import sxb from '../../assets/layerTree/属性表@2x.png'
import ysj from '../../assets/layerTree/元数据@2x.png'
import select from '@/assets/layerTree/自定义图层选中.png'
import unselect from '../../assets/layerTree/自定义图层未选中.png'
import AddGroupModal from './components/addGroupModal.vue'
import IconDropDownYear from './components/IconDropDownYear.vue';
import { initWmtsMap, removeLayer, initTerrainMap, init3dTiles } from "@/mixin/server";
import { getLayerType, getLayerTree, updateDefaultLayer, getLayerDetail } from "@/api/layer";


const { proxy } = getCurrentInstance();
const layerStore = useLayerStore();
const defaultProps = {
  children: 'children',
  label: 'label'
}
const addGroupModalRef = ref(null);
const treeRef = ref(null); // 获取树形控件的引用
const allExpanded = ref(false);
const treeData = ref([]); // 树形图数据
const customLasyer = ref() // 选中图层id
const showPanelNo = ref(0) // 当前显示的面板
const loadingTree = ref(false) // 树形图加载状态
const menuConfig = ref([
  { key: 'node-collect', name: '收藏', src: sc },
  { key: 'zoom-to-layer', name: '全图', src: qt },
  { key: 'node-timing', name: '时间抽', src: sjz },
  { key: 'node-table', name: '属性表', src: sxb },
  { key: 'node-property', name: '元数据', src: ysj },
])

const customLayerList = ref([]) // 自定义图层列表;

onMounted(() => {
  getLayerData();
})
// 计算属性绑定底部背景
const wrapperStyle = computed(() => {
  // 根据不同的面板编号返回不同的背景样式
  switch (showPanelNo.value) {
    case 0:
      return {
        "background": `url(${customLayerBg}) no-repeat center / cover`
      }
    case 1:
      return {
        "--el-select-wrapper-background": `url(${allLayerBg}) no-repeat center / cover`
      }
    case 2:
      return {
        "--el-select-wrapper-background": `url(${allLayerBg}) no-repeat center / cover`
      }
    case 3:
      return {
        "--el-select-wrapper-background": `url(${djLayerBg}) no-repeat center / cover`
      }
  }
})
// 添加获取节点样式类的方法
const getNodeClass = (level) => {
  return `node-level-${level}`
}
// 修改层级样式
const getNodeStyle = (node, data) => {
  if (data.year) {
    return {
      marginLeft: `10px`,
    }
  }
}
const getSelectIcon = (item) => {
  // 如果当前项是默认项
  if (item.isDefault) {
    return select;
  }
  // 如果所有项都没有默认值，且当前项是第一个
  if (customLayerList.value.every(i => !i.isDefault) && customLayerList.value[0]?.id === item.id) {
    return select;
  }
  // 其他情况显示未选中图标
  return unselect;
}
// 获取图层类型
const getLayerData = async () => {
  loadingTree.value = true;
  const res = await getLayerType({ catalogType: '0' });
  console.log('res', res)
  if (res.code === 200) {
    customLayerList.value = res.data.sort((a, b) => a.orderNum - b.orderNum);
    const arr = customLayerList.value.filter(i => i.isDefault); // 存在默认图层
    if (arr.length > 0) {
      customLasyer.value = arr[0]?.id;
    } else {
      customLasyer.value = customLayerList.value[0]?.id;
    }
    await getLayerTreeData();
  }
  loadingTree.value = false;
}

// 修改默认图层
const handleUpdateDefaultLayer = async (id) => {
  const res = await updateDefaultLayer({ id, isDefault: true });
  if (res.code === 200) {
    proxy.$modal.msgSuccess('修改默认图层成功');
    getLayerData();
  }
}
// 监听图层类型变化
const changeCustomLayer = (val) => {
  console.log('val', val)
  customLasyer.value = val;
  getLayerTreeData();
}
// 获取图层tree
const getLayerTreeData = async () => {
  const res = await getLayerTree({ parentCatalogId: customLasyer.value, catalogType: '0' }); // 获取图层树
  treeData.value = res.data;
}
// 修改面板
const changePanel = async (index) => {
  loadingTree.value = true;
  if (index === 0) {
    getLayerTreeData();
  } else if (index === 1) {
    // 全部
    // 1791626951761551360 综合基础库
    const res = await getLayerTree({ parentCatalogId: '1791626951761551360', catalogType: '0' }); // 获取图层树
    treeData.value = res.data;
  } else if (index === 2) {
    // 收藏
  }
  showPanelNo.value = index;
  loadingTree.value = false;
}

// tree过滤
const filterNode = (value, data) => {
  if (!value) return true;
  return data.nodeName.indexOf(value) !== -1;
}
// 展开全部
const toggleAllItems = () => {
  allExpanded.value = !allExpanded.value;
  if (allExpanded.value) {
    Object.values(treeRef.value.store.nodesMap).forEach((v) => v.expand());
  } else {
    Object.values(treeRef.value.store.nodesMap).forEach((v) => v.collapse());
  }
}
// 图层选中，添加选中图层
const handleCheck = async (data, obj) => {
  const layerNodes = [];

  const processNode = async (node) => {
    console.log('node', node)
    if (node.nodeType === 1) {
      try {
        const detailRes = await getLayerDetail(node.defaultId);
        if (detailRes.code === 200) {
          const layerData = detailRes.data;
          layerNodes.push(layerData);
          addLayer(layerData);
        }
      } catch (error) {
        console.error("获取图层详情失败：", error);
      }
    }
    if (node.children && node.children.length) {
      for (const child of node.children) {
        await processNode(child);
      }
    }
  };

  await processNode(data);
  layerStore.checkLayer = layerNodes;
}

// 图层选中，添加选中图层
const addLayer = (data) => {
  switch (data.type) {
    case 'wmts':
      initWmtsMap(data);
      break;
    case 'terrain':
      initTerrainMap(data);
      break;
    case '3dtiles':
      init3dTiles(data);
      break;
  }
}

// 添加分组
const addGroup = (data) => {
  addGroupModalRef.value.openDialog(data);
};
// 删除分组
const deleteGroup = () => {
  proxy.$modal.confirm('是否确认删除分组名称为"' + '测试' + '"的数据项？').then(function () {
    // return delNotice(noticeIds);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
// 上移
const moveUp = (data) => {
  proxy.$modal.msgSuccess("上移成功");

}
// 下移
const moveDown = (data) => {
  proxy.$modal.msgSuccess("下移成功");
}
</script>

<style scoped lang="scss">
.tree-container {
  padding: 10px;
  color: #fff;
  overflow: auto;
  max-height: 810px;

  .tree-header {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: end;


    .expand-all-btn {
      display: flex;
      align-items: center;
      color: #fff;
      font-size: 14px;
      cursor: pointer;
      padding-right: 12px;

      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }
  }

  :deep(.el-tree) {
    background-color: transparent;
    color: #fff;

    // 修改三角形图标
    .el-tree-node__expand-icon {
      width: 20px;

      svg {
        display: none;
      }

      &.expanded {
        transform: none;

        &::before {
          content: '';
          display: inline-block;
          width: 20px;
          height: 20px;
          background: url('@/assets/layerTree/收起.png') no-repeat center;
          background-size: contain;
        }
      }

      &:not(.expanded) {
        transform: none;

        &::before {
          content: ' ';
          display: inline-block;
          width: 20px;
          height: 20px;
          background: url('@/assets/layerTree/展开.png') no-repeat center;
          background-size: contain;
        }
      }
    }

    .el-tree-node__content {
      background-color: transparent;
      height: auto;
      padding: 6px 0;

      &:hover {
        background-color: transparent;
      }

      .el-checkbox {
        margin-right: 8px;

        .el-checkbox__input {
          vertical-align: middle;

          &.is-checked {
            .el-checkbox__inner {
              background-color: transparent;
              border-color: transparent;

              &::after {
                content: ' ';
                background: url('@/assets/layerTree/打开图层@2x.png') no-repeat center;
                background-size: contain;
                border: none;
                width: 20px;
                height: 20px;
                position: absolute;
                left: -1px;
                top: -1px;
                transform: none;
              }
            }
          }
        }

        .el-checkbox__inner {
          background-color: transparent;
          border-color: transparent;
          width: 20px;
          height: 20px;
          position: relative;

          &::after {
            content: ' ';
            background: url('@/assets/layerTree/关闭图层@2x.png') no-repeat center;
            background-size: contain;
            width: 20px;
            height: 20px;
            position: absolute;
            left: -1px;
            top: -1px;
            transform: none;
          }
        }
      }

      .custom-tree-node {
        display: flex;
        align-items: center;
        width: 100%;
        padding: 6px;
        border-radius: 4px;
        position: relative;

        &:hover {
          .item-text {
            color: #38FFCE !important;
          }

          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            border-radius: 4px;
            border: 1px solid transparent;
            background: linear-gradient(45deg, #00E1BB, #008DDC) border-box;
            -webkit-mask:
              linear-gradient(#fff 0 0) padding-box,
              linear-gradient(#fff 0 0);
            -webkit-mask-composite: destination-out;
            mask-composite: exclude;
          }
        }

        .expand-icon {
          margin-right: 8px;
          transition: transform 0.3s;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;

          img {
            width: 20px;
            height: 20px;
          }
        }

        .node-content {
          display: flex;
          align-items: center;
          flex: 1;
          position: relative;

          .folder-icon {
            width: 20px;
            height: 20px;
            margin-right: 8px;
          }

          .visibility-icon {
            margin-right: 12px;
            font-size: 16px;
            color: #fff;
            cursor: pointer;

            >img {
              width: 20px;
              height: 20px;
            }
          }

          .item-text {
            font-size: 14px;
            color: #fff;
          }

          .item-count {
            margin-left: 8px;
            color: #fff;
            font-size: 12px;
          }

          .yearSelect {
            width: 70px !important;
            text-align: right;
            position: absolute;
            right: 30px;

            .el-select__wrapper {
              background-color: transparent;
              border-radius: 20px;
              height: 10px !important;
              border: 1px solid #777F91;
              box-shadow: none !important;

              .el-select__selected-item {
                color: #fff;
                text-align: center;
              }
            }
          }

          .move-btns {
            position: absolute;
            right: 20px;
            display: flex;
            align-items: center;

            >img {
              width: 20px;
              height: 20px;
            }
          }

          .more {
            position: absolute;
            right: 0px;
            transform: rotate(90deg);
          }
        }
      }
    }
  }
}

.bottom-tabs {
  position: absolute;
  width: 100%;
  height: 40px;
  bottom: 0px;
  display: flex;
  align-items: center;

  .item-custom {
    width: 140px !important;
    height: 40px;
    font-weight: bold;

    ::v-deep .el-dropdown {
      border: none !important;
      width: 100% !important;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
    }

    .dropdown-trigger {
      display: flex;
      align-items: center;
      justify-content: center;

      span {
        font-size: 15px;
      }
    }
  }

  .common-css {
    width: 80px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    font-weight: bold;
    background: var(--el-select-wrapper-background, none);
    background-size: 99.9%;
  }

  .item-all {}

  .item-collect {}

  .item-overlay {}
}

// 第1层级样式
::v-deep.node-level-1 {

  .item-text {
    font-weight: bold;
  }

  .item-count {
    font-size: 12px;
    font-weight: bold !important;
  }
}

// 隐藏滚动条
::-webkit-scrollbar {
  width: 0;
  height: 0;
}
</style>
